<?php

/**
 * API接口返回数据
 * @param type $message 消息
 * @param type $statusCode 状态码(200:成功,300:失败,301:超时)
 * @param type $data
 */
function apiReturn($message, $statusCode = 200, $data = array()) {
    $ret = array(
        'message' => $message,
        'statusCode' => $statusCode,
        'data' => $data,
    );
    echo json_encode($ret, JSON_UNESCAPED_UNICODE);
    exit;
}

/**
 * ajax返回数据
 * @param type $message 消息
 * @param type $statusCode 状态码(200:成功,300:失败,301:超时)
 * @param type $data 数据
 * @param type $forward 跳转url
 * @param type $forwardConfirm 跳转url提示信息
 * @param type $tabid 刷新navtab
 * @param type $dialogid 刷新dialog
 * @param type $closeCurrent 是否关闭当前窗口
 */
function ajaxReturn($message, $statusCode = 200, $data = array(), $forward = '', $forwardConfirm = '', $tabid = '', $dialogid = '', $closeCurrent = false) {
    $ret = array(
        'message' => $message,
        'statusCode' => $statusCode,
        'data' => $data,
        'forward' => $forward,
        'forwardConfirm' => $forwardConfirm,
        'tabid' => $tabid,
        'dialogid' => $dialogid,
        'closeCurrent' => $closeCurrent,
    );
    echo json_encode($ret, JSON_UNESCAPED_UNICODE);
    exit;
}

/**
 * 生成树型数据
 * @param type $items 数组数据
 * @param type $id ID字段名
 * @param type $pid 父级ID字段名
 * @param type $son 子类数组下标名
 */
function genTree($items, $id = 'id', $pid = 'pid', $son = 'child') {
    $tree = array();
    $tmpMap = array();

    foreach ($items as $item) {
        $tmpMap[$item[$id]] = $item;
    }

    foreach ($items as $item) {
        if (isset($tmpMap[$item[$pid]])) {
            $tmpMap[$item[$pid]][$son][] = &$tmpMap[$item[$id]];
        } else {
            $tree[] = &$tmpMap[$item[$id]];
        }
    }
    unset($tmpMap);
    return $tree;
}

/**
 * 上传多个文件上传
 * @param type $config 配置数组
 */
function upload($config = array()) {
    if (empty($config)) {
        $config = C('UPLOAD_CONFIG');
    } else {
        $config = array_merge(C('UPLOAD_CONFIG'), $config);
    }

    $up = new \Think\Upload($config);
    $info = $up->upload();
    return $info;
}

/**
 * 上传单个文件
 * @param type $file 上传文件
 * @param type $config 配置数组
 */
function uploadOne($file, $config = array()) {
    if (empty($config)) {
        $config = C('UPLOAD_CONFIG');
    } else {
        $config = array_merge(C('UPLOAD_CONFIG'), $config);
    }

    $up = new \Think\Upload($config);
    $info = $up->uploadOne($file);
    return $info;
}

/**
 * 实例alioss
 */
function newAlioss() {
    vendor('Alioss.autoload');

    $config = C('ALIOSS_CONFIG');
    $oss = new \OSS\OssClient($config['KEY_ID'], $config['KEY_SECRET'], $config['END_POINT']);
    return $oss;
}

/**
 * 上传文件到alioss
 * @param type $path 本地图片路径
 */
function aliossUploadOne($path) {
    $bucket = C('ALIOSS_CONFIG.BUCKET');
    // 先统一去除左侧的.或者/ 再添加./
    $oss_path = ltrim($path, './');
    $path = './' . $oss_path;
    if (file_exists($path)) {
        // 实例化oss类
        $oss = newAlioss();
        // 上传到oss    
        $oss->uploadFile($bucket, $oss_path, $path);
        // 如需上传到oss后 自动删除本地的文件 则删除下面的注释 
        @unlink(realpath($path));
        return true;
    }
    return false;
}

/**
 * 获取图片路径
 * @param type $path 本地图片路径
 */
function getImgUrl($path) {
    if (empty($path)) {
        return '';
    }
    $path = '/' . ltrim($path, './');
    $alioss = C('ALIOSS_CONFIG');
    if (empty($alioss['KEY_ID'])) {
        return 'http://' . $_SERVER['HTTP_HOST'] . $path;
    } else {
        return 'http://' . $alioss['BUCKET'] . '.' . $alioss['END_POINT'] . $path;
    }
}

/**
 * 验证码
 */
function showVerify($id = '', $config = array()) {
    if (empty($config)) {
        $config = C('VERIFY_CONFIG');
    }
    $verify = new \Think\Verify($config);
    $verify->entry($id);
}

/**
 * 检测验证码
 */
function checkVerify($code, $id = '') {
    $verify = new \Think\Verify();
    return $verify->check($code, $id);
}

/**
 * 权限验证
 */
function checkRule($rule) {
    if (empty(session('userInfo.id'))) {
        return false;
    }

    $myAuth = new \Common\Lib\MyAuth();

    return $myAuth->check($rule, session('userInfo.id'));
}

/**
 * 导出数据为Excel
 * @param array $fieldArr 标题数组
 * @param array $dataArr 数据数组
 */
function exportExcel($fieldArr, $dataArr) {
    if (empty($fieldArr) || empty($dataArr)) {
        echo '数据不能为空';
        return;
    }
    vendor('PHPExcel.PHPExcel');
    //创建PHPExcel对象
    $obj = new PHPExcel();
    //创建excel写入对象
    $writer = new PHPExcel_Writer_Excel5($obj);
    //得到当前工作表对象
    $curSheet = $obj->getActiveSheet();

    $fieldNum = count($fieldArr);
    $dataRow = count($dataArr) + 2;

    for ($col = 0; $col < $fieldNum; ++$col) {
        $cellName = PHPExcel_Cell::stringFromColumnIndex($col) . '1';
        $curSheet->setCellValue($cellName, $fieldArr[$col]);
    }

    for ($row = 2; $row < $dataRow; ++$row) {
        for ($col = 0; $col < $fieldNum; ++$col) {
            $cellName = PHPExcel_Cell::stringFromColumnIndex($col) . $row;
            $curSheet->setCellValue($cellName, $dataArr[$row - 2][$col]);
        }
    }

    $fileName = date('YmdHis', time());
    header('Content-Type: application/vnd.ms-execl');
    header('Content-Disposition: attachment;filename="' . $fileName . '.xls"');
    header('Cache-Control: max-age=0');
    $writer->save('php://output');
}

/**
 * 生成二维码
 * @param type $data 信息数据
 * @param type $size 二维码图大小,1-10可选,数字越大图片尺寸越大
 * @param type $path 图片保存根路径
 * @param type $level 纠错比例,分为L,M,Q,H四个等级,H代表最高纠错能力
 */
function createQR($data = '', $size = 8, $path = './Qr', $level = 'L') {
    if (empty($data) || empty($size) || empty($path) || empty($level)) {
        return false;
    }
    vendor('QRcode.phpqrcode');
    $size = min(max((int) $size, 1), 10);
    $filePath = $path . '/' . date('Ym');
    if (!file_exists($filePath)) {
        @mkdir($filePath, 0766, true);
    }
    if (!in_array($level, array('L', 'M', 'Q', 'H'))) {
        $level = 'L';
    }
    $fileName = date('YmdHis') . '_' . uniqid() . '.png';
    $file = $filePath . '/' . $fileName;

    QRcode::png($data, $file, $level, $size, 2);

    if (file_exists($file)) {
        return $file;
    } else {
        return false;
    }
}

/**
 * 验证手机号码
 * @author Pirlo.21 <375057009@qq.com>
 * @param $phone 手机号码
 */
function verifyPhone($phone = '') {
    $status = false;
    if (preg_match("/^1[34578]{1}\d{9}$/", $phone)) {
        $status = true;
    }
    return $status;
}

/**
 * 创建或进入目录，linux上
 * @param string $save_path 除了文件名之外的路径
 */
function createDir($save_path) {
    if (!@chdir($save_path)) {
        $arr = explode('/', $save_path);
        if ($arr) {
            $new_src_dir = '';
            foreach ($arr as $item) {
                if (empty($item)) {
                    continue;
                }
                $new_src_dir .= '/' . $item;
                if (!@chdir($new_src_dir)) {
                    echo $new_src_dir . "<br />";
                    mkdir($new_src_dir, 0777);
                    chmod($new_src_dir, 0777);
                    chdir($new_src_dir);
                }
            }
        }
    }
}

/**
 * 生成图片
 * @param string $file_name 文件全路径
 * @param string $pic_binary 二进制流
 * @param string $mode 参数指定了所要求到该流的访问类型
 * @return 成功则返回文件字节数，失败则返回False
 */
function createPic($file_name, $pic_binary, $mode = 'wb') {
    $resource = @fopen($file_name, $mode);
    if ($resource == FALSE) {
        return false;
    }
    $rs = @fwrite($resource, $pic_binary);
    fclose($resource);
    return $rs;
}
